package com.etime.shyauth.config;

import com.etime.shyauth.dto.CurrentUser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 工具类
 * @author zw
 */
@Component
public class Tools {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 从redis缓存中获取当前登录的用户
     * @param token 用户令牌
     * @return 当前登录用户的信息。如果返回null则表示用户没有登录或者登录过期
     */
    public CurrentUser getCurrentUserFromRedis(String token){
        if(token == null || token.equals("")){
            return null;
        }
        CurrentUser user = null;
        if(stringRedisTemplate.hasKey(token)){
            //从reids中获取用户登录信息
            String str = stringRedisTemplate.boundValueOps(token).get();
            //重置过期时间(redis缓存不过期)
            //stringRedisTemplate.boundValueOps(token).expire(30, TimeUnit.MINUTES);
            ObjectMapper om = new ObjectMapper();
            try {
                user = om.readValue(str,CurrentUser.class);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                user = null;
            }
        }
        return user;
    }
}
